package com.zx.flow.core.execute.eventhandler;

import com.zx.flow.api.config.FlowConfig;
import com.zx.flow.api.config.FlowConfigNode;
import com.zx.flow.api.dict.FlowDict.Event;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.execute.request.FlowParamCreate;
import com.zx.flow.api.execute.request.FlowParamStart;
import com.zx.flow.api.execute.request.FlowParamSubFlow;
import com.zx.flow.api.execute.response.FlowResult;
import com.zx.flow.api.util.FlowDataUtil;
import com.zx.flow.api.util.OperatorsUtil;
import com.zx.flow.core.execute.EventHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 事件处理器【流程->子流程】
 */
@Slf4j
public class EventFlowSubFlowHandler extends EventHandler<FlowParamSubFlow> {

    @Override
    public boolean in(FlowContext flow, FlowParamSubFlow param) {
        return true;
    }

    @Override
    public FlowResult on(FlowContext flow, FlowParamSubFlow param) {
        FlowContext parentFlow = param.getParentFlow();
        FlowNode parentNode = this.getNode(param.getParentFlow().getId(), param.getNodeId());
        FlowConfig config = this.getFlowConfig(parentFlow.getFlowConfigCode(), parentFlow.getFlowConfigId());
        FlowConfigNode parentNodeConfig = config.getNode(parentNode.getNodeCurrentCode());
        log.info("创建子流程, flowId={}, nodeId={}, subFlowCode={}",
                parentNode.getFlowId(), parentNode.getId(), parentNodeConfig.getSubFlowCode());

        // 创建子流程
        FlowResult subFlowResult = this.execute(new FlowParamCreate(parentNodeConfig.getSubFlowCode(),
                "[子流程]" + parentFlow.getTitle(), parentFlow.getApplyReason(), OperatorsUtil.getSystemCode(),
                parentFlow.getExtendData()));
        FlowContext subFlow = subFlowResult.getFlowContext();
        // 开始子流程
        this.execute(new FlowParamStart(subFlow.getId()));

        FlowNode subFlowNode = FlowDataUtil.getCurrent(subFlow);
        // 填充数据
        parentNode.setSubFlowId(subFlowNode.getFlowId());
        subFlow.setParentFlowId(parentFlow.getId());
        subFlow.setParentNodeId(parentNode.getId());
        // 保存数据
        this.saveFlow(subFlow);
        this.saveNode(parentFlow.getId(), parentNode);

        // 触发监听
        this.listener(parentNode, Event.subFlowStart);

        return FlowResult.ok(flow);
    }
}
